<?php

namespace App\Logic\Admin;

use App\Logic\BaseLogic;
use App\Models\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class UsermenberLogic extends BaseLogic
{

    private $request;

    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    /**
     * 获取当条数据
     * @param $id
     * @return Admin
     */
    public function one($id)
    {
        $Admin = Admin::find($id);
        return $Admin;
    }

    /**
     * @return mixed
     */
    public function insert()
    {
        // 外部参数
        $request = $this->request;

        // 验证
        $validator = Validator::make($request->input(), [
            'username' => ['required', Rule::unique('admin_users')],
            'email' => ['required', 'email', Rule::unique('admin_users')],
            'name' => ['required', Rule::unique('admin_users')],
        ]);
        if ($validator->fails()) {
            return $validator;
        }

        //保存数据
        $Admin = new Admin([
            "username" => $request->username,
            "email" => $request->email,
            "password" => $request->password,
            "avatar" => "/head/default.jpeg",
            "name" => $request->name
        ]);
        $this->uploadFile($Admin); //上传图片
        $status = $Admin->save();

        // 返回
        return $status;
    }

    /**
     * @param Admin $Admin
     * @return mixed
     */
    public function save(&$Admin)
    {
        // 外部参数
        $request = $this->request;

        // 保存数据
        $Admin->username = $request->username;
        $Admin->email = $request->email;
        if (!empty($request->password)) {
            $Admin->password = $request->password;
        }
        $this->uploadFile($Admin);
        $status = $Admin->save();

        // 返回
        return $status;
    }

    /**
     * @var Admin
     * @return mixed
     */
    public function del($id){
        $Admin = Admin::find($id);//找到模型
        $status = $Admin->delete();
        return $status;
    }

    /**
     * @param Admin $Admin
     */
    private function uploadFile(&$Admin)
    {

        // 上传图片
        if ($this->request->hasFile('file')) {

            $disk = Storage::disk();
            $file = $this->request->file('file');

            // 删除文件
            if (!empty($Admin['avatar'])) {
                $disk->delete($Admin['avatar']);
            }

            // 重命名文件
            $fileName = md5($file->getClientOriginalName() . time() . rand()) . '.' . $file->getClientOriginalExtension();
            $fileAddress = 'head/image_' . $fileName;

            // 上传图片
            $bool = $disk->put($fileAddress, file_get_contents($file->getRealPath()));

            if ($bool) {
                $Admin->avatar = $fileAddress;
            }
        }
    }

}